module cl {
	export class FlyEffect {
        constructor(private map : CampaignPage, private flyObj : eui.Group,
                srcCood : Coord, tgtCoord : Coord,
                private reachcb : ()=>void, private endcb : ()=>void) {
            let vec01 = Vector.fromTo(srcCood, tgtCoord);
            vec01 = vec01.asLength(38 + 88);
            let vertvecs = vec01.verticalVectors();

            let coords : Coord[][] = [
                    [vertvecs[0].applyTo(srcCood)],
                    [vertvecs[1].applyTo(srcCood)]];
            let heading0 = vertvecs[0].heading();
            let heading1 = vertvecs[1].heading();
            let heading01 = vec01.heading();

            let rotate0 = heading01 - heading0;
            if (Math.abs(rotate0) > 180) {
                rotate0 += -(rotate0 / Math.abs(rotate0)) * 360;
            }
            let rotate1 = heading01 - heading1;
            if (Math.abs(rotate1) > 180) {
                rotate1 += -(rotate1 / Math.abs(rotate1)) * 360;
            }
            let segments = 4;
            for (let step = 0; step < segments; step++){
                coords[0].push(Util.coordDegreeOffset(tgtCoord.x, tgtCoord.y, heading0 + (step / segments) * rotate0, 38 + 88));
            }
            for (let step = 0; step < segments; step++){
                coords[1].push(Util.coordDegreeOffset(tgtCoord.x, tgtCoord.y, heading1 + (step / segments) * rotate1, 38 + 88));
            }
            coords[0].push(vec01.applyTo(tgtCoord));
            this.flyRoute = coords[0].concat(coords[1].reverse());
        }

        private flyid : number;
        private flyRoute : Coord[];

        public start() : void {
            this.flyid = 0;
            this.flyObj.x = this.flyRoute[0].x;
            this.flyObj.y = this.flyRoute[0].y;
            this.map.groupEffect.addChild(this.flyObj);
            this.step();
        }

        private step() : void {
            let vec = Vector.fromTo(this.flyRoute[this.flyid], this.flyRoute[this.flyid+1]);
            let time = Math.floor(vec.len() * 0.6); // 常数 0.6 为每像素移动0.6毫秒

            Util.setOrientation(this.flyObj.getChildAt(1), Map.tileEngine.headingIndex(vec.heading()));
            egret.Tween.get(this.flyObj).to(this.flyRoute[this.flyid+1], time);

            if (this.flyid == Math.floor(this.flyRoute.length / 2)) {
                this.reachcb();
            }

            if (++this.flyid < this.flyRoute.length - 1) {
                setTimeout(this.step.bind(this), time+1);
            } else {
                setTimeout(this.end.bind(this), time+1);
            }
        }

        private end() : void {
            this.map.groupEffect.removeChild(this.flyObj);
            this.endcb();
        }
    }
}